<template>
  <div class="min-h-screen bg-gradient-to-br from-purple-50 via-indigo-50 to-blue-50">
    <!-- 导航栏 -->
    <NavBar :showDashboard="false" />

    <!-- 主要内容 -->
    <div class="py-8 px-4 sm:px-6 lg:px-8">
      <div class="w-full max-w-[98%] mx-auto">
        <!-- 页面标题 -->
        <div class="mb-8">
          <h1 class="text-3xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-purple-600 via-indigo-600 to-blue-600">
            ZiYue 文档管理
          </h1>
          <p class="mt-2 text-gray-600">管理和追踪所有文档的校对进度</p>
        </div>

        <!-- 快速访问区域 -->
        <div class="grid grid-cols-1 gap-6 mb-8">
          <!-- 进行中的任务 -->
          <div class="bg-white/60 backdrop-blur-sm rounded-xl border border-purple-100/20 shadow-lg p-6">
            <div class="flex items-center justify-between mb-4">
              <h2 class="text-xl font-semibold text-gray-800">进行中的任务</h2>
              <div class="flex items-center gap-4">
                <span class="text-sm text-gray-500">{{ inProgressDocuments.length > 0 ? `${inProgressDocuments.length} 个任务` : '暂无任务' }}</span>
              </div>
            </div>
            <div v-if="inProgressDocuments.length > 0" class="space-y-4">
              <div
                v-for="doc in inProgressDocuments.slice(0, 3)"
                :key="doc.id"
                class="bg-white/40 rounded-lg p-4"
              >
                <div class="flex items-center justify-between">
                  <span class="text-sm font-medium text-gray-900">{{ doc.title }}</span>
                  <div class="flex items-center gap-3">
                    <span
                      class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                      :class="{
                        'bg-gray-100 text-gray-800': doc.step === 0,
                        'bg-blue-100 text-blue-800': doc.step === 1,
                        'bg-purple-100 text-purple-800': doc.step === 2,
                        'bg-green-100 text-green-800': doc.step === 3
                      }"
                    >
                      {{ getStepText(doc.step) }}
                    </span>
                    <button
                      @click="handleCheck(doc)"
                      class="px-3 py-1 bg-indigo-100 text-indigo-700 hover:bg-indigo-200 rounded-md text-sm font-medium transition-colors duration-200"
                    >
                      继续校对
                    </button>
                  </div>
                </div>
              </div>
              <div v-if="inProgressDocuments.length > 3" class="text-center">
                <button
                  @click="handleViewAllInProgress"
                  class="text-sm text-indigo-600 hover:text-indigo-500"
                >
                  查看全部
                </button>
              </div>
            </div>
            <div v-else class="bg-gradient-to-br from-indigo-50 to-purple-50 rounded-lg p-6 border border-indigo-100/20">
              <div class="flex flex-col items-center text-center">
                <div class="w-16 h-16 bg-indigo-100 rounded-full flex items-center justify-center mb-4">
                  <DocumentIcon className="w-8 h-8 text-indigo-600" />
                </div>
                <h3 class="text-lg font-medium text-gray-900 mb-2">暂无进行中的任务</h3>
                <p class="text-sm text-gray-500 mb-4">您可以从下方文档列表中选择一篇开始校对</p>
                <PrimaryButton @click="scrollToDocumentList">
                  <template #icon>
                    <CheckCircleIcon className="w-4 h-4 mr-2" />
                  </template>
                  浏览文档列表
                </PrimaryButton>
              </div>
            </div>
          </div>
        </div>

        <!-- 过滤器和操作区 -->
        <div class="mb-6 flex flex-wrap items-center justify-between gap-4">
          <div class="flex flex-wrap gap-2">
            <button
              v-for="(key, step) of steps"
              :key="key"
              @click="() => handleStepChange(key)"
              :class="[
                'px-4 py-2 rounded-lg text-sm font-medium transition-colors duration-200',
                key === currentStep
                  ? 'bg-indigo-600 text-white shadow-md'
                  : 'bg-white/60 text-gray-600 hover:bg-indigo-50'
              ]"
            >
              {{ step }}
            </button>
          </div>
        </div>

        <!-- 文档列表 -->
        <div class="document-list-container">
          <DocumentList 
            :documents="documents" 
            :loading="loading"
            :inProgressDocuments="inProgressDocuments"
            @check="handleCheck"
            @view="handleView"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../../utils/request'
import { useAuthStore } from '../../stores/auth'
import NavBar from '../../components/NavBar.vue'
import PrimaryButton from '../../components/ui/PrimaryButton.vue'
import CheckCircleIcon from '../../components/icons/CheckCircleIcon.vue'
import LockIcon from '../../components/icons/LockIcon.vue'
import DocumentIcon from '../../components/icons/DocumentIcon.vue'
import DocumentList from './components/DocumentList.vue'

const router = useRouter()
const authStore = useAuthStore()
const documents = ref([])
const loading = ref(false)
const currentStep = ref('')
const inProgressDocuments = ref([])

const steps = {
  '全部': '',
  '未开始': '0',
  '第一次校对': '1',
  '第二次校对': '2',
  '第三次校对': '3'
}

// 获取步骤文本
const getStepText = (step) => {
  const stepTexts = {
    0: '未开始',
    1: '第一次校对',
    2: '第二次校对',
    3: '第三次校对'
  }
  return stepTexts[step] || '未知状态'
}

const handleStepChange = async (step) => {
  currentStep.value = step
  await fetchDocuments()
}

const fetchDocuments = async () => {
  loading.value = true
  try {
    const result = await request.get('/documents/', {
      params: currentStep.value ? { step: currentStep.value } : {}
    })
    if (result.code === 200) {
      documents.value = result.data
    }
  } catch (error) {
    console.error('获取文档列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取正在进行中的文档
const fetchInProgressDocuments = async () => {
  try {
    const result = await request.get('/documents/', {
      params: { 
        in_progress: true,
        user_id: authStore.user?.id // 确保使用可选链操作符
      }
    })
    if (result.code === 200) {
      inProgressDocuments.value = result.data
    }
  } catch (error) {
    console.error('获取进行中的文档失败:', error)
  }
}

// 处理查看全部进行中的文档
const handleViewAllInProgress = () => {
  // 将步骤过滤器设置为空（全部）
  currentStep.value = ''
  // 滚动到文档列表
  scrollToDocumentList()
}

// 处理文档校对
const handleCheck = (doc) => {
  router.push(`/document/proofread/${doc.id}`)
}

// 处理文档查看
const handleView = (doc) => {
  router.push(`/document/view/${doc.id}`)
}

// 滚动到文档列表区域
const scrollToDocumentList = () => {
  // 找到文档列表组件
  const documentListElement = document.querySelector('.document-list-container')
  if (documentListElement) {
    // 平滑滚动到该元素
    documentListElement.scrollIntoView({ 
      behavior: 'smooth',  // 平滑滚动
      block: 'start'       // 滚动到元素顶部对齐视窗
    })
  } else {
    console.warn('未找到文档列表元素')
  }
}

// 页面加载时自动获取全部文档和进行中的文档
onMounted(async () => {
  // 设置当前步骤为全部（空字符串）
  currentStep.value = ''
  
  // 并行获取所有文档和进行中的文档
  await Promise.all([
    fetchDocuments(),
    fetchInProgressDocuments()
  ])
})
</script>

